<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" :inline="true">
      <el-form-item  prop="clientCode">
        <el-input v-model="queryParams.clientCode" placeholder="Client Code" clearable style="width: 180px;" />
      </el-form-item>
      <el-form-item  prop="fullName">
        <el-input v-model="queryParams.fullName" placeholder="Full Name" clearable style="width: 280px;" />
      </el-form-item>
      <el-form-item>
       
        <el-button type="primary" icon="search"  v-hasPermi="['client:get']" @click="search">{{
          $t("ship.button.search")
        }}</el-button>
         <SearchReset :query-params="queryParams" @reset="resetQuery"/>
        <el-button type="primary"  plain icon="Plus" @click="addClickEvent"  v-hasPermi="['client:add']" >
          {{ $t("ship.button.plus") }}
        </el-button> 
        <el-button type="warning" plain  icon="download" @click="exportClickEvent"  v-hasPermi="['client:export']" >
          {{ $t("ship.button.export") }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-table class="daf-table" ref="tableRef" stripe :border="true" :data="listData" style="width: 100%" @sort-change="handleSortChange">
    <el-table-column prop="clientCode" label="Client Code" width="120"  show-overflow-tooltip/>
    <el-table-column prop="fullName" label="Full Name In English" width="200"  show-overflow-tooltip/> 
    <el-table-column prop="cnFullName" label="Full Name In Chinese" width="220"  show-overflow-tooltip/> 
    <el-table-column prop="contact" label="Contact Person" width="140"/>
    <el-table-column prop="mobile" label="Phone/Mobile" width="130"  show-overflow-tooltip/>
    <el-table-column prop="country" label="Country" width="130" show-overflow-tooltip/>  
    <el-table-column prop="registrationNumber" label="REGISTRATION NUMBER"  width="180" show-overflow-tooltip/> 
    <el-table-column prop="registrationAddress" label="REGISTRATION Address" width="180"  show-overflow-tooltip/>  
    <el-table-column prop="email" label="E-MAIL ADDRESS" width="130" show-overflow-tooltip/>  
    <el-table-column prop="photo" label="Business License" min-width="150" > 
      <template #default="scope" > 
        <PreViewImageUpload :isDelSub="true" :record="scope.row" :photos="Array.isArray(scope.row.photos)?scope.row.photos:scope.row.photos?[scope.row.photos]:[]" :url="uploadUrl" :id="scope.row.clientId" @onDelete="submitUploadForm" @onSuccess="submitUploadForm" />
      </template>
    </el-table-column>   
  <el-table-column prop="status" label="Status" width="150"   v-hasPermi="['client:edit']">
      <template #default="scope">
        <!-- <el-tag v-if="scope.row.status == 2" type="warning">{{ statuss[scope.row.status] }}</el-tag>
        <el-tag v-if="scope.row.status == 1" type="success">{{ statuss[scope.row.status] }}</el-tag>
        <el-tag v-if="scope.row.status == 0">{{ statuss[scope.row.status] }}</el-tag> -->
        <el-select
              v-model="scope.row.status"
              class="ipt"
              clearable 
              :disabled="scope.row.status == 1 || scope.row.satus == 2"
              @change="handleStatus(scope.row)"
            >
              <el-option :key="index" :label="item" :value="index" v-for="(item,index) in  statuss"  />
        </el-select>
      </template>  
    </el-table-column>  

    <el-table-column prop="createBy" label="Created By" width="120" />
    <el-table-column label="Operation" width="200"  v-hasPermi="['client:edit']" fixed="right">
      <template #default="scope">
        <span class="btn-primary"  @click="editClickEvent(scope.row)">{{$t("ship.button.edit")}}</span>&nbsp;&nbsp;
        <span class="btn-primary" :disabled="scope.row.status == 1" @click="removeClickEvent(scope.row.clientId)">{{
          $t("ship.button.remove")
        }}</span>&nbsp;&nbsp;
        <span class="btn-primary"   @click="bankInfoClickEvent(scope.row.clientId)">{{
          $t("ship.button.bankInfo")
        }}</span>
      </template>
    </el-table-column>
  </el-table>
  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="1000" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible"  >
    <el-form :model="formParam" :rules="rules" ref="custForm" label-width="180px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="Client Code" prop="clientCode" required>
            <el-input v-model="formParam.clientCode" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col> 
        <el-col :span="12">
          <el-form-item label="Full Name In English" prop="fullName" required>
            <el-input v-model="formParam.fullName" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Full Name In Chinese" prop="cnFullName" required>
            <el-input v-model="formParam.cnFullName" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col> 
        <el-col :span="12">
          <el-form-item label="Phone/Mobile" prop="mobile" required>
            <el-input v-model="formParam.mobile" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col> 
      </el-row>
      <el-row>        
        <el-col :span="12">
          <el-form-item label="Contact Person" prop="contact" required>
            <el-input v-model="formParam.contact" placeholder="Please input" /> 
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="country" label="COUNTRY">
            <el-input v-model="formParam.country" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row> 
        <el-col :span="24"> 
          <el-form-item prop="registrationAddress" label="REGISTRATION ADDRESS">
            <el-input v-model="formParam.registrationAddress" placeholder="REGISTRATION ADDRESS"></el-input>
          </el-form-item>
        </el-col>
      </el-row> 
      <el-row> 
        <el-col :span="12">
          <el-form-item label="REGISTRATION NUMBER" prop="registrationNumber" >
            <el-input v-model="formParam.registrationNumber" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="E-MAIL ADDRESS" prop="email" >
            <el-input v-model="formParam.email" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
        }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>

      </span>
    </template>
  </el-dialog>

  <el-dialog :width="500" destroy-on-close draggable title="Uplod" v-model="showUploadPictures">
    <el-form ref="custForm">
      <el-row>
        <!-- 图片   :headers="headerObj"-->
        <el-col :span="12">
          <el-upload
            v-if="isPhoto"
            class="upload-demo"
            action="#"
            multiple
            :limit="5"
            accept=".jpg,.png,.jpeg"
            :http-request="HttpRequest"
            :on-success="HttpRequesSuccess"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <el-button type="primary" v-if="photos.length < 5">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">jpg/png files with a size less than 1Mb.</div>
            </template>
          </el-upload>

          <el-upload
            v-else
            v-model:file-list="tallys"
            class="upload-demo"
            action="#"
            :limit="5"
            accept=".pdf"
            :http-request="HttpRequest"
            :on-success="HttpRequesSuccess"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
          >
            <el-button type="primary" v-if="tallys.length < 5">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">pdf files with a size less than 1Mb.</div>
            </template>
          </el-upload>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="uploadPicturesCancel">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" @click="submitUploadForm">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog :width="500" destroy-on-close draggable title="DownLoad" v-model="showDownLoadPictures">
    <el-row :gutter="24">
      <!-- 图片 -->
      <div class="demo-image__preview" v-if="isPhoto" v-for="(item, index) in photos" :key="index">
        <el-col :span="6">
          <el-image style="width: 100px; height: 100px" :src="item" fit="cover" @click="handlePreview(item)" />
        </el-col>
      </div>
      <transition-group v-else class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
        <li :key="index" class="el-upload-list__item ele-upload-list__item-content" v-for="(url, index) in tallys">
          <el-link :href="url" :underline="false" target="_blank">
            <span class="el-icon-document" @click="downloadFileHandel(url)"> {{ getFileName(url) }} </span>
          </el-link>
        </li>
      </transition-group>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="downLoadPicturesCancel">{{ $t("ship.button.cancel") }}</el-button>
        <!-- <el-button type="primary" @click="submitUploadForm">{{ $t("ship.button.submit") }}</el-button> -->
      </span>
    </template>
  </el-dialog>  
  <ClientModal ref="addFormModal" @refreshTable="refreshTable" />
</template>
<script lang="ts" setup name="client">
import { ref, onMounted, reactive } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import service from "@/utils/request";
import moment from "moment";
import type {  UploadUserFile } from "element-plus";
import ClientModal from "./clientModal.vue";
import PreViewImageUpload from '@/components/ImageUpload/PreViewImageUpload.vue'  
import { downloadFile } from "@/utils/downloadFile"; 
import { useTableDrag } from '@/hooks/useHooks'
const { tableRef, proxy } = useTableDrag();
const uploadUrl='/shipping/client/upload'
const delUrl='/basicData/supplier'
const router = useRouter();
const custForm = ref(null);
const addFormModal = ref();
const dialogTitle = ref("");

const showUploadPictures = ref(false);

const showDownLoadPictures = ref(false);

const initForm = {
  title: null,
  clientId: null,
  fullName: null,
  cnFullName:null,
  clientCode: null,
  contact: null,
  mobile: null,
  email: null,
  country: 'P.R.CHINA',
  registrationAddress:null,
  registrationNumber:null, 
};
const formParam = reactive(Object.assign({}, initForm)); 
const total = ref(0);
const statuss = ['UnApprove', "Approve", "Reject"]
const mailValid = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("email can't be blank"));
  } else if (!/^(?:\w+\.?)*\w+@(?:\w+\.)*\w+$/.test(value)) {
    callback(new Error('The email format is illegal!'));
  } else {
    callback();
  }
}
const rules = ref({
  mail: [{ required: true, trigger: "blur", validator: mailValid }]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  clientCode: null,
  fullName: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/client/getTable", { params: queryParams });
  listData.value = result.data;
  total.value = result.total;
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    refreshTable()
}
const handleStatusChange =async(row) => {
      let text = row.status === 1 ? "approve" : "reject";
      ElMessageBox.confirm('Cconfirm to "' + text + '""' + row.fullName + '"?')
        .then( () => {
            service.put("shipping/client", row);
        })
        .then(() => {
          // @ts-ignore
          ElNotification.success(text + " success");
        })
        .catch(()=> {
          row.status = row.status === "0" ? "1" : "0";
        });
    }
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => { 
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  dialogFormVisible.value = true
  dialogTitle.value = "Update Client"
  isAdd = false 
};

const handleStatus=(row:any)=>{
    if(row.status != null && row.status != 0){
      ElMessageBox.confirm("Confirm to update the client Status？", "Confirmation Information", {
          type: "warning",
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel",
        }).then(async () => { 
          await service.put(`shipping/client`, row);
          ElNotification.success({
            title: "Prompt information",
            message: "Update booking status success!",
            position: "bottom-right"
          });
          
        });
    }
}


const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/client/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};
 

let isAdd = false;
const loading = ref(false);
const photos = ref<UploadUserFile[]>([]);
const addClickEvent = () => { 
  dialogFormVisible.value = true
  dialogTitle.value = "Add Client"
  isAdd = true
  Object.assign(formParam, initForm);
  //addFormModal.value.show();
};


const exportClickEvent = ()=>{
  downloadFile("/shipping/client/export", queryParams, `${moment( new Date()).format('YYYYMMDD')}_client.xlsx`);
}

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
 
    await service[isAdd ? "post" : "put"]("shipping/client", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    refreshTable()
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
}; 

const uploadFile = async (event) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/country/uploadFile", formData);
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

//绑定银行信息
const bankInfoClickEvent = (id) => {
  router.push({ path: "/basicData/bankInfo", query: { id: id,type:0} })
}

const submitDeleteImg = async (data) => { 
  await service["post"]("/shipping/client/deleteFile", { id: data.id, url: data.delfile });
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "delete successful!",
    position: "bottom-right"
  });
  refreshTable();
};
 
const submitUploadForm = async (data) => { 
  // @ts-ignore
  const params = {
    clientId: data.id,
    photos: data.photos  };

  await service["put"]("/shipping/client/updatePhotos", params);
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};

onMounted( ()=>{
  refreshTable();
}
 );
</script>
<style lang="scss" scoped>
.el-table__expand-column .cell {
  display: none;
}
::v-deep.el-table td.el-table__cell div{
    text-align: center;
  }
.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}
</style>
